﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Diagnostics;
using System.Linq;
using System;
using Kinlo.Entitys;
using Kinlo.WebApi.Model;
using XCode;

namespace WebApplication1.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class plateController : ControllerBase
    {
        [HttpGet("hehe")]
        public string Get()
        {
            return "ssss";
        }

        [HttpPost("reqplate")]
        //[Route("api/plate/reqplate")]
        public PlateResponse Get(PlateRequest req)
        {
            var sw = new Stopwatch();
            sw.Start();
            var rsp = new PlateResponse();
            try
            {
                try
                {
                    //var reqRaw = Request.Content.ReadAsStringAsync();
                    //$"【WEB服务】请求内容:{JsonConvert.SerializeObject(reqRaw.Result)}".Info("Log", LevelType.Info, false);
                    rsp.Key = req.Key;
                    rsp.TrayNo = req.TrayNo;
                    if (!string.IsNullOrEmpty(req.TrayNo))
                    {

                        var trayId = Plate.FindMax("TrayID", Plate._.TrayBarcode == req.TrayNo);

                        var batts = Plate.FindAll(Plate._.TrayID == trayId);

                        //var trayId = DB.Query<string>($"select max(trayId) from plate where trayBarcode='{req.TrayNo}'").FirstOrDefault();
                        //var exp = $"where  trayId='{trayId}'";
                        //var batts = DB.GetListAsync<Plate>(exp).Result;
                        if (batts != null && batts.Count() > 0)
                        {
                            var indexs = Enumerable.Range(1, 256);
                            var datas = from i in indexs
                                        join f in batts
                                        on i equals f.SeqNo into items
                                        from item in items.DefaultIfEmpty()
                                        select new PlateItem
                                        {
                                            Position = i,
                                            BatteryCode = item?.Barcode ?? "",
                                            BatteryStatus = String.IsNullOrEmpty(item?.Barcode) ? 2 : 1
                                        };
                            rsp.Items.AddRange(datas);
                            rsp.CellBatch = batts.FirstOrDefault(s => !string.IsNullOrEmpty(s.CellBatch))?.CellBatch ?? "";
                            rsp.CellType = batts.FirstOrDefault(s => !string.IsNullOrEmpty(s.CellType))?.CellType ?? "";
                            rsp.Code = 1;
                        }
                        else
                        {
                            rsp.Code = 2;
                            rsp.Message = $"没有找到对应的装盘数据 {req.TrayNo}";
                        }
                    }
                }
                catch (Exception ex)
                {
                    rsp.Code = 3;
                    rsp.Message = ex.InnerException.Message ?? ex.Message;
                }
                return rsp;
            }
            finally
            {
                //$"【WEB服务】耗时:{sw.ElapsedMilliseconds} 返回结果:{JsonConvert.SerializeObject(rsp)}".Info("Log", LevelType.Info, false);
            }
        }


        [HttpPost("uploadinfo")]
        //[Route("api/plate/uploadinfo")]
        public PrechargeRsp AddPrechargeOCVData(PrechargeDto req)
        {
            var sw = new Stopwatch();
            sw.Start();
            var rsp = new PrechargeRsp();
            try
            {
                try
                {
                    //var reqRaw = Request.Content.ReadAsStringAsync();
                    //$"【WEB服务】请求内容:{JsonConvert.SerializeObject(reqRaw.Result)} {sw.ElapsedMilliseconds}".Info("Log", LevelType.Info, false);

                    if (!string.IsNullOrEmpty(req.TrayCode))
                    {
                        //string table = req.ProcessNO.ToUpper().Contains("OCV0") ? "ocv" : "precharge";
                        string table = req.ProcessNO.ToUpper().Contains("OCV0") ? "OCV" : "Plate";
                        //DB.Execute($"update {table} set flag=1 where traycode='{req.TrayCode}'; ");

                        if (table.Contains("OCV"))
                        {

                            var ocvData = OCV.FindAll(OCV._.TrayCode == req.TrayCode);
                            ocvData.ToList().ForEach(item =>
                            {
                                item.Flag = 1;
                            });

                            ocvData.Update();
                        }
                        else
                        {
                            var prechargeData = Precharge.FindAll(OCV._.TrayCode == req.TrayCode);
                            prechargeData.ToList().ForEach(item =>
                            {
                                item.Flag = 1;
                            });

                            prechargeData.Update();
                        }

                        var tickId = DateTime.Now.Ticks;
                        var msg = "";
                        if (req.BatteryList.Count == 256)
                        {
                            //ProductionCounter.Tmp.Load();
                            for (int i = 0; i < req.BatteryList.Count; i++)
                            {
                                var batt = req.BatteryList[i];

                                var batt1 = new OCV
                                {
                                    TrayID = tickId,
                                    TrayCode = req.TrayCode,
                                    ProcessNO = req.ProcessNO,
                                    Flag = 0,
                                    //Position = i + 1,
                                    Position = batt.Position,
                                    BatteryCode = batt.BatteryCode,
                                    BatteryStatus = batt.BatteryStatus,
                                    NGCode = batt.NGCode,
                                    IR = batt.IR,
                                    Voltage = batt.Voltage,
                                    Steptype = batt.Steptype,
                                    Current = batt.Current,
                                    Capacity = batt.Capacity,
                                    Energy = batt.Energy,
                                };
                                int? code = -1;
                                if (table.Contains("OCV"))
                                {
                                    batt1.Insert();
                                    //code = DB.Insert<OCV>(batt1);
                                    //if (batt.BatteryStatus == 1)
                                    //{
                                    //    ProductionCounter.Tmp.OKCount++;
                                    //}
                                    //else if (batt.BatteryStatus == 2)
                                    //{
                                    //    ProductionCounter.Tmp.NGCount++;
                                    //}
                                    //else
                                    //{
                                    //    ProductionCounter.Tmp.NullCount++;
                                    //}
                                }
                                else
                                {
                                    //code = DB.Insert<Precharge>(batt1.ToPrecharge());
                                    var batt2 = ToPrecharge(batt1).Insert();
                                }

                                //if (code <= 0)
                                //{
                                //    //$"【WEB服务】{batt1.BatteryCode}数据保存失败 {table}".Info("Log", LevelType.Info, false);
                                //    msg = "保存失败";
                                //}
                            }
                            rsp.Message = "";
                            rsp.Code = 1;
                            //if (!string.IsNullOrEmpty(msg))
                            //{
                            //    rsp.Message = "数据保存失败";
                            //    rsp.Code = 2;
                            //}
                            //else
                            //{
                            //    rsp.Message = "";
                            //    rsp.Code = 1;
                            //}
                            //if (table == "ocv")
                            //ProductionCounter.Tmp.Save();
                        }
                        else
                        {
                            msg = $"数据条目不匹配 期待256,实际{req.BatteryList.Count} ";
                            rsp.Message = msg;
                            rsp.Code = 2;
                        }
                    }
                    else
                    {
                        rsp.Message = "托盘号不正确";
                        rsp.Code = 2;
                    }
                }
                catch (Exception ex)
                {
                    //$"【WEB服务】服务发生异常:{ex}".Info("Log", LevelType.Info, false);
                    rsp.Code = 3;
                    rsp.Message = ex.InnerException.Message ?? ex.Message;
                }
                return rsp;
            }
            finally
            {
                //$"【WEB服务】耗时:{sw.ElapsedMilliseconds} 返回结果:{JsonConvert.SerializeObject(rsp)}".Info("Log", LevelType.Info, false);
            }
        }
        [HttpPost("reqocv")]
        //[Route("api/plate/reqocv")]
        public OCVResponse GetOCV(OCVRequest req)
        {
            var sw = new Stopwatch();
            sw.Start();
            var rsp = new OCVResponse();
            try
            {
                try
                {
                    //var reqRaw = Request.Content.ReadAsStringAsync();
                    //$"【WEB服务】请求内容:{JsonConvert.SerializeObject(reqRaw.Result)}".Info("Log", LevelType.Info, false);
                    //rsp.Key = req.Key;
                    //rsp.TrayNo = req.TrayNo;
                    if (!string.IsNullOrEmpty(req.TrayNo))
                    {

                        var trayId = OCV.FindMax("TrayID", OCV._.TrayCode == req.TrayNo);

                        var batts = OCV.FindAll(Plate._.TrayID == trayId).OrderBy(batt => batt.Position).ToList();


                        //var trayId = DB.Query<string>($"select max(trayId) from ocv where TrayCode='{req.TrayNo}'").FirstOrDefault();
                        //var exp = $"where  trayId='{trayId}'";
                        //var batts = DB.GetListAsync<OCV>(exp)
                        //.Result
                        //.OrderBy(batt => batt.Position)
                        //.ToList();
                        if (batts != null && batts.Count() > 0)
                        {
                            rsp.Message = ""; // 设置响应消息

                            foreach (var batt in batts)
                            {
                                var item = new OCVItem();
                                item.TrayCode = batt.TrayCode;
                                item.ProcessNo = batt.ProcessNO;
                                item.BatteryCode = batt.BatteryCode;
                                item.Position = batt.Position;
                                item.BatteryStatus = batt.BatteryStatus;
                                item.NGCode = batt.NGCode;
                                item.flag = batt.Flag;
                                rsp.Items.Add(item);
                            }

                            rsp.CellBatch = "";
                            rsp.CellType = "";
                            rsp.Code = 1;
                        }
                        else
                        {
                            rsp.Code = 2;
                            rsp.Message = $"没有找到对应的装盘数据 {req.TrayNo}";
                        }
                    }
                }
                catch (Exception ex)
                {
                    rsp.Code = 3;
                    rsp.Message = ex.InnerException.Message ?? ex.Message;
                }
                return rsp;
            }
            finally
            {
                //$"【WEB服务】耗时:{sw.ElapsedMilliseconds} 返回结果:{JsonConvert.SerializeObject(rsp)}".Info("Log", LevelType.Info, false);
            }
        }


        [HttpGet("platetest")]
        //[Route("api/plate/test")]
        public string Test()
        {
            try
            {
                return $"Test {DateTime.Now}";
            }
            catch (Exception ex)
            {
                return $"Test {ex.Message}";
            }
        }

        public Precharge ToPrecharge(OCV _ocv)
        {
            return new Precharge
            {
                BatteryCode = _ocv.BatteryCode,
                BatteryStatus = _ocv.BatteryStatus,
                Flag = _ocv.Flag,
                NGCode = _ocv.NGCode,
                Position = _ocv.Position,
                ProcessNO = _ocv.ProcessNO,
                TrayCode = _ocv.TrayCode,
                TrayID = _ocv.TrayID,

                IR = _ocv.IR,
                Voltage = _ocv.Voltage,
                Steptype = _ocv.Steptype,
                Current = _ocv.Current,
                Capacity = _ocv.Capacity,
                Energy = _ocv.Energy,
            };
        }
    }
}
